package com.wchen.project.zk.demo;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @Desc:
 * @author: cww
 * @DateTime: 2020/1/17 8:32
 */

public class ZookeeperConnectWithSIDPassword implements Watcher {
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    public static void main(String[] args) throws IOException, InterruptedException {
        ZooKeeper zooKeeper = new ZooKeeper("home:2181",5000,new ZookeeperConnectWithSIDPassword());
        connectedSemaphore.await();
        System.out.println("Connected Success!");
        long sessionId = zooKeeper.getSessionId();
        byte[] password = zooKeeper.getSessionPasswd();
        // 先测试一下错误的session id 和 password
        zooKeeper = new ZooKeeper("home:2181", 500, new ZookeeperConnectWithSIDPassword(), 1l, "test".getBytes());
        zooKeeper = new ZooKeeper("home:2181", 500, new ZookeeperConnectWithSIDPassword(), sessionId, password);
        Thread.sleep(5000);

    }
    @Override
    public void process(WatchedEvent watchedEvent) {
        System.out.println("Receive watched event:" + watchedEvent);
        if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
            connectedSemaphore.countDown();
        }
    }
}
